import axios from "axios";
import { useLoginStore } from "@/stores/loginStore"

import type { AxiosError, AxiosResponse } from "axios";
import type { RequestConfig, RequestInterceptorsConfig, ApiResponse } from '@/interface/Axios'
import { message } from "ant-design-vue";
import type { LoginRes } from "@/interface/LoginRes";


/* 创建请求实例 */
const service = axios.create({
    baseURL: import.meta.env.Ex_Base_Url,
    timeout: 30000,
});

function loginStore() {
    return useLoginStore();
}


const whiteList = ["user/login"];
/* 添加请求拦截器 */
service.interceptors.request.use(
    (config: RequestInterceptorsConfig) => { // 请求拦截
        if (loginStore().loginInfo.token && !whiteList.includes(config.url as string)) {
            config.headers.Auth = loginStore().loginInfo.token
        }
        return config;
    },
    (error: AxiosError) => { // 请求错误拦截
        return Promise.reject(error);
    }
);




/* 添加响应拦截器 */
service.interceptors.response.use(
  ( response: AxiosResponse<ApiResponse<any>> ) : any => { // 响应成功处理函数
      if(response.data.code === 5005 || response.data.code === 4001) {
          message.error(response.data.msg);
          loginStore().loginInfo = {} as LoginRes;
          setTimeout(()=> {
              window.location.href = "/";
          },2000)
      }else if(response.data.code === 4003) {
          message.error(response.data.msg);
      }
      return response;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);


/* 封装实例的请求方法 */
export default async function request<T>(config: RequestConfig) {
    // axios实例的 request 接受的第一个泛型参数，就是返回数据data的类型
    return service.request<ApiResponse<T>>(config).then((res) => res.data); // 返回axios的里data数据
}



